package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    @Override
    public PageResult page(DishPageQueryDTO dishPageQueryDTO) {
        PageHelper.startPage(dishPageQueryDTO.getPage(),dishPageQueryDTO.getPageSize());
        List<DishVO> list = dishMapper.page(dishPageQueryDTO);
        Page page = (Page) list;
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void save(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        dish.setStatus(StatusConstant.DISABLE);
        dishMapper.save(dish);
//        Long dishId = dish.getId();
//        DishFlavor dishFlavor = new DishFlavor();
//        dishDTO.getFlavors().forEach(flavor -> dishFlavor.setDishId(dishId));
//        dishFlavorMapper.insertFlavor(dishFlavor);
    }

    @Override
    public void startOrStop(Integer status, Long id) {
        Dish dish = new Dish();
        dish.setStatus(status);
        dish.setId(id);
        dishMapper.startOrStop(dish);
    }

    @Override
    public DishVO getById(Long id) {
        DishVO dishVO =dishMapper.getById(id);
        return dishVO;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void update(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        dishMapper.update(dish);
        Long dishId = dish.getId();
        dishFlavorMapper.delete(dishId);
        DishFlavor dishFlavor = new DishFlavor();
        dishDTO.getFlavors().forEach(flavor -> dishFlavor.setDishId(dishId));
        dishFlavorMapper.insertFlavor(dishFlavor);
    }

    @Override
    public List<DishVO> list(Long categoryId) {
        return dishMapper.list(categoryId);
    }

    @Override
    public void delete(List<Long> ids) {
        dishMapper.delete(ids);
    }
}
